#include <../inc/uart.h>



int uart_init(int fd){
    struct termios options;

    if(tcgetattr(fd,&options)<0){
        perror("tcgetattr error\n");
        return (-1);
    }
    
    cfsetispeed(&options,BAUDRATE);
    cfsetospeed(&options,BAUDRATE);

    options.c_cflag &=~CSIZE;
    options.c_cflag |=CS8;
    options.c_cflag &=~PARENB;
    options.c_cflag &=~CSTOPB;

    options.c_cflag |=(CLOCAL | CREAD);

    options.c_iflag &=~(IXON |IXOFF |IXANY);

    options.c_lflag &=~(ICANON | ECHO | ECHOE | ISIG);

    options.c_oflag &=~OPOST;
    options.c_cc[VMIN]=0;
    options.c_cc[VTIME]=1;

    if(tcsetattr(fd,TCSANOW,&options)<0){
        perror("tcsetattr failed\n");
        return (-1);

    }

    return 0;
}

int uart_send(int fd,const char *data,int len){
    int sent=0;

    while(sent<len){
        int n = write(fd,data+sent,len-sent);

        if(n<0){
            perror("write error\n");
            return (-1);
        }
        sent+=n;
    }
    return sent;
}

int uart_read(int fd,const char *buf,int max_len){
    int total=0;

    
    while(total<max_len){
        int n = read(fd,buf+total,max_len-total);

        if(n<0){
            if(errno==EAGAIN || errno ==EWOULDBLOCK){
                break;
            }
            perror("read failed\n");
            return (-1);
        }
        else if(n==0){
            break;
        }
        total+=n;
    }
    return total;
}

int sent_to_tjc(int temp){

    int fd;
    char tx_buf[256];
    char rx_buf[256]={0};

    if((fd=open(UART_DEVICE,O_RDWR | O_NOCTTY | O_NDELAY))<0){
        perror("open uart device failed\n");

        return (-1);
    }

    if(uart_init(fd)<0){
        close(fd);
        return (-1);
    }
    sprintf(tx_buf,"x0.val=%d\xff\xff\xff",(int)(100*temp));
    printf("sending temp: %s\n",tx_buf);
    if(uart_send(fd,tx_buf,strlen(tx_buf))<0){
        close(fd);
        return (-1);
    }

}

void clear_serial_buffer(int fd){

    tcflush(fd,TCIFLUSH);
}   